package com.hubiao.basics.thread;

/**
 * Description 死锁案例
 *
 * @author hubiao
 * @since 2021-01-17 22:17
 */
public class DeadLockDemo {

    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    public static void main(String[] args) {
        new Thread( new DeadLockTest1( lock1, lock2 ) ).start();
        new Thread( new DeadLockTest2( lock1, lock2 ) ).start();
    }

}

class DeadLockTest1 implements Runnable {

    private Object lock1;
    private Object lock2;

    public DeadLockTest1(Object lock1, Object lock2) {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }

    @Override
    public void run() {
        synchronized (lock1) {
            System.out.println( " My Thread One start " );
            try {
                Thread.sleep( 1000 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock2) {
            }
            System.out.println( " My Thread One end " );
        }
    }
}

class DeadLockTest2 implements Runnable {

    private Object lock1;
    private Object lock2;

    public DeadLockTest2(Object lock1, Object lock2) {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }

    @Override
    public void run() {
        synchronized (lock2) {
            System.out.println( " My Thread Two start " );
            try {
                Thread.sleep( 1000 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock1) {
            }
            System.out.println( " My Thread Two end " );
        }
    }
}
